import { ElMessage, ElMessageBox } from 'element-plus';
import { useProductApi } from '/@/api/product';

const { getGoodsTagList, addGoodsTag, updateGoodsTag, delGoodsTag } = useProductApi();

export const useInit = () => {
	const state = reactive({
		dialoagTitle: '编辑标签',
		isAdd: false,
		dialogVisible: false,
		tableData: [],
		loading: false,
		deleteLoading: false,
		tagName: '',
		page: {
			pageSize: 10,
			current: 1,
			total: 0,
		},
		tagId: -1,
	});

	const getlist = async () => {
		try {
			let res = await getGoodsTagList(state.page);
			if (res.code === 200) {
				state.tableData = res.data.data;
			}
		} catch (err) {
			ElMessage.error('获取列表失败');
		}
	};

	const onOpenAdd = () => {
		state.isAdd = true;
		state.tagName = '';
		state.dialoagTitle = '添加标签';
		state.dialogVisible = true;
	};

	const closeDetailDialog = () => {
		state.dialogVisible = false;
	};

	const closeDialog = () => {
		closeDetailDialog();
	};

	return {
		state,
		getlist,
		onOpenAdd,
		closeDialog,
	};
};

export const useEdit = (state) => {
	// 设置详情的id
	const setDetailId = (item) => {
		state.isAdd = false;
		state.dialogVisible = true;
		state.tagId = item.id;
		state.tagName = item.tagName;
	};

	return {
		setDetailId,
	};
};

export const useSave = (getList) => {
	const submitSave = async (state) => {
		let res = state.isAdd ? await addGoodsTag({ tagName: state.tagName }) : await updateGoodsTag({ tagName: state.tagName, id: state.tagId });
		if (res.code === 200) {
			getList();
			ElMessage.success('保存成功！');
			state.dialogVisible = false;
		}
	};

	return {
		submitSave,
	};
};

export const useDel = (getList) => {
	const onSubmitDel = async (id) => {
		try {
			let res = await delGoodsTag({ id });
			if (res.code === 200) {
				getList();
				ElMessage.success('删除成功!');
			}
		} catch (err) {
			ElMessage.error('删除失败！');
		}
	};

	const beforeDelete = (row) => {
		ElMessageBox.confirm(`确认删除：${row.tagName}? 标签`, '删除标签', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		})
			.then(() => {
				onSubmitDel(row.id);
			})
			.catch(() => {});
	};
	return {
		beforeDelete,
	};
};
